package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.query.BpmnInfoQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.config.SystemConfig;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.common.util.StringUtils;
import cn.wolfcode.car.common.util.file.FileUploadUtils;
import cn.wolfcode.car.common.util.file.FileUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.compress.compressors.FileNameUtil;
import org.apache.commons.compress.utils.FileNameUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

//%test%

@Service
@Transactional
public class BpmnInfoServiceImpl implements IBpmnInfoService {

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;

    @Autowired
    private RepositoryService repositoryService;


    @Override
    public TablePageInfo<BpmnInfo> query(BpmnInfoQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<BpmnInfo>(bpmnInfoMapper.selectForList(qo));
    }


    @Override
    public BpmnInfo get(Long id) {
        return bpmnInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public void save(String bpmnInfoFile, String bpmnType, String info) {
        if (StringUtils.isEmpty(bpmnInfoFile)) {
            throw new BusinessException("请上传文件");
        }
        if (StringUtils.isEmpty(bpmnType)) {
            throw new BusinessException("流程类型不为空");
        }

        String type = FileNameUtils.getExtension(bpmnInfoFile);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(SystemConfig.getProfile(), bpmnInfoFile));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new BusinessException("流程部署异常");
        }

        Deployment deployment = null;
        if ("zip".equalsIgnoreCase(type)) {
            ZipInputStream zipInputStream = new ZipInputStream(inputStream);
            deployment = repositoryService.createDeployment().
                    addZipInputStream(zipInputStream).deploy();
        } else if ("bpmn".equalsIgnoreCase(type) || "xml".equalsIgnoreCase(type)) {
            deployment = repositoryService.createDeployment().
                    addInputStream(bpmnInfoFile, inputStream).deploy();
        }

        if (deployment == null) {
            throw new BusinessException("流程部署失败");
        }

        //创建bpmnInfo对象

        BpmnInfo bpmnInfo = new BpmnInfo();

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                deploymentId(deployment.getId()).latestVersion().singleResult();

        bpmnInfo.setActProcessId(processDefinition.getId());
        bpmnInfo.setActProcessKey(processDefinition.getKey());
        bpmnInfo.setDeployTime(new Date());
        bpmnInfo.setDeploymentId(deployment.getId());
        bpmnInfo.setBpmnName(processDefinition.getName());
        bpmnInfo.setBpmnType(bpmnType);
        bpmnInfo.setInfo(info);
        bpmnInfoMapper.insert(bpmnInfo);
    }


    @Override
    public void update(BpmnInfo bpmnInfo) {
        bpmnInfoMapper.updateByPrimaryKey(bpmnInfo);
    }

    @Override
    public void delete(Long id) {

       if(id==null){
           throw new BusinessException("参数异常");
       }
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByPrimaryKey(id);

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                deploymentId(bpmnInfo.getDeploymentId()).latestVersion().singleResult();


        //Todo 对流程中的单进行状态恢复

        //删除流程定义
        repositoryService.deleteDeployment(bpmnInfo.getDeploymentId(),true);

        //清除文件
        File file = new File(SystemConfig.getProfile(),processDefinition.getResourceName());
        if (file.exists()) {
            file.delete();
        }

        //清除对于bpmninfo数据表
        bpmnInfoMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<BpmnInfo> list() {
        return bpmnInfoMapper.selectAll();
    }

    @Override
    public String uploadFiles(MultipartFile file) {
        if (file == null || file.getSize() == 0) {
            throw new BusinessException("传入文件为空");
        }

        String type = FileNameUtils.getExtension(file.getOriginalFilename());

        if (!("zip".equalsIgnoreCase(type) || "xml".equalsIgnoreCase(type) || "bpmn".equalsIgnoreCase(type))) {
            throw new BusinessException("非法文件传入");
        }

        String upload = null;
        try {
            InputStream in = file.getInputStream();
            upload = FileUploadUtils.upload(SystemConfig.getProfile(), file);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("文件上传异常");
        }
        return upload;

    }

    @Override
    public InputStream readResource(String deploymentId, String type) throws FileNotFoundException {
        if(StringUtils.isEmpty(deploymentId)||StringUtils.isEmpty(type)){
            throw new BusinessException("传入参数有误");
        }

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().
                deploymentId(deploymentId).latestVersion().singleResult();
        if("xml".equalsIgnoreCase(type)){
            processDefinition = repositoryService.createProcessDefinitionQuery().
                    deploymentId(deploymentId).latestVersion().singleResult();
            String resourceName = processDefinition.getResourceName();
            return new FileInputStream(new File(SystemConfig.getProfile(),resourceName));
        }else if("png".equalsIgnoreCase(type)){
            BpmnModel model = repositoryService.getBpmnModel(processDefinition.getId());
            ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
            InputStream inputStream = generator.generateDiagram(model, Collections.EMPTY_LIST, Collections.EMPTY_LIST,
                    "宋体","宋体","宋体");
            return inputStream;
        }

        return null;
    }

    @Override
    public void updataInfo(Long id, String info) {
        if(id==null||StringUtils.isEmpty(info)){
            throw new BusinessException("参数异常");
        };
        bpmnInfoMapper.updateInfoById(id,info);
    }

    @Override
    public BpmnInfo queryByName(String bpmn_name) {
        return bpmnInfoMapper.selectByName(bpmn_name);
    }


}
